﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using bzxxxt.admin.entity;
using bzxxxt.admin.service;
using bzxxxt.bll;
using bzxxxt.dal;
using bzxxxt.model;
using System.IO;

namespace bzxxxt.admin.ashx
{
    /// <summary>
    /// bg_grave_ext 的摘要说明
    /// </summary>
    public class bg_grave_ext : rm_base
    {
        GraveBLL graveBLL = new GraveBLL();
        public override void add(HttpContext context)
        {
            string paradisecode = context.Request.Params["ui_grave_paradise_code"] ?? "";
            string hourse = context.Request.Params["ui_grave_hourseNum"] ?? "0";
            if (string.IsNullOrEmpty(hourse)) hourse = "1";

            string floor = context.Request.Params["ui_grave_floorNum"] ?? "0";
            if (string.IsNullOrEmpty(floor)) floor = "0";

            string section = context.Request.Params["ui_grave_sectionNum"] ?? "0";
            if (string.IsNullOrEmpty(section)) section = "0";

            string line = context.Request.Params["ui_grave_lineNum"] ?? "0";
            if (string.IsNullOrEmpty(line)) line = "0";
            line = "00" + line;
            line = line.Substring(line.Length - 2);

            string row = context.Request.Params["ui_grave_rowNum"] ?? "0";
            if (string.IsNullOrEmpty(row)) row = "0";

            string col = context.Request.Params["ui_grave_colNum"] ?? "0";
            if (string.IsNullOrEmpty(col)) col = "0";

            string type = context.Request.Params["ui_grave_type"] ?? "1";
            if (string.IsNullOrEmpty(type)) type = "1";

            string price = context.Request.Params["ui_grave_price"] ?? "0";
            if (string.IsNullOrEmpty(price)) price = "0";

            string qty = context.Request.Params["ui_grave_qty"] ?? "0";
            if (string.IsNullOrEmpty(qty)) qty = "0";

            string description = context.Request.Params["ui_grave_description"] ?? "";

            int hourseNum = int.Parse(hourse);
            int floorNum = int.Parse(floor);
            section = Utils.getSectionStr(section);
            
            //int lineNum = int.Parse(line);
            int rowNum = int.Parse(row);
            int colNum = int.Parse(col);

            char c = Convert.ToChar('A' + int.Parse(type) - 1);            
            string loc =  string.Format("{0:000}{1}{2:00}{3:00000}{4:0}", paradisecode, Utils.getSectionStr4Bit(section), line, colNum, c);
            tbGrave grave = new tbGrave
            {                
                location = loc,
                name = string.Format("{0}区{1:00}排{2:00000}号", section, line, colNum),
                hourseNum = string.Format("{0:0}", hourseNum),
                floorNum = string.Format("{0:0}", floorNum),
                sectionNum = section,
                lineNum = string.Format("{0:00}", line),
                layerNum = string.Format("{0:00}", rowNum),
                columnNum = string.Format("{0:000}", colNum),
                qty = int.Parse(qty),
                graveType = int.Parse(type),
                price = float.Parse(price),
                description = description
            };

            context.Response.Write(graveBLL.Add(grave, paradisecode));
        }

        public override void edit(HttpContext context)
        {
            string id = context.Request.Params["ui_grave_id"] ?? "0";
            string paradisecode = context.Request.Params["ui_grave_paradise_code"] ?? "";
            string hourse = context.Request.Params["ui_grave_hourseNum"] ?? "0";
            if (string.IsNullOrEmpty(hourse)) hourse = "1";

            string floor = context.Request.Params["ui_grave_floorNum"] ?? "0";
            if (string.IsNullOrEmpty(floor)) floor = "0";

            string section = context.Request.Params["ui_grave_sectionNum"] ?? "0";
            if (string.IsNullOrEmpty(section)) section = "0";

            string line = context.Request.Params["ui_grave_lineNum"] ?? "0";
            if (string.IsNullOrEmpty(line)) line = "0";
            line = "00" + line;
            line = line.Substring(line.Length - 2);

            string row = context.Request.Params["ui_grave_rowNum"] ?? "0";
            if (string.IsNullOrEmpty(row)) row = "0";

            string col = context.Request.Params["ui_grave_colNum"] ?? "0";
            if (string.IsNullOrEmpty(col)) col = "0";

            string type = context.Request.Params["ui_grave_type"] ?? "1";
            if (string.IsNullOrEmpty(type)) type = "1";

            string price = context.Request.Params["ui_grave_price"] ?? "0";
            if (string.IsNullOrEmpty(price)) price = "0";

            string qty = context.Request.Params["ui_grave_qty"] ?? "0";
            if (string.IsNullOrEmpty(qty)) qty = "0";

            string description = context.Request.Params["ui_grave_description"] ?? "";

            int hourseNum = int.Parse(hourse);
            int floorNum = int.Parse(floor);
            section = Utils.getSectionStr(section);

            //int lineNum = int.Parse(line);
            int rowNum = int.Parse(row);
            int colNum = int.Parse(col);

            char c = Convert.ToChar('A' + int.Parse(type) - 1);
            string loc = string.Format("{0:000}{1}{2:00}{3:00000}{4:0}", paradisecode, Utils.getSectionStr4Bit(section), line, colNum, c);
            tbGrave grave = new tbGrave
            {
                id = int.Parse(id),
                location = loc,
                name = string.Format("{0}区{1:00}排{2:00000}号", section, line, colNum),
                hourseNum = string.Format("{0:0}", hourseNum),
                floorNum = string.Format("{0:0}", floorNum),
                sectionNum = section,
                lineNum = string.Format("{0:00}", line),
                layerNum = string.Format("{0:00}", rowNum),
                columnNum = string.Format("{0:000}", colNum),
                qty = int.Parse(qty),
                graveType = int.Parse(type),
                price = float.Parse(price),
                description = description
            };
            context.Response.Write(graveBLL.Edit(grave, paradisecode));
        }

        public override void delete(HttpContext context)
        {
            string ids = context.Request.Params["id"];
            context.Response.Write(graveBLL.Delete(ids));
        }

        public override void getall(HttpContext context)
        {
            string where = context.Request.Params["where"] ?? "1=1";
            int pageIndex = CommUtil.GetPageIndex(context);
            int pageSize = CommUtil.GetPageSize(context);
            string mySort = CommUtil.GetSort(context) + " " + CommUtil.GetOrder(context);

            context.Response.Write(graveBLL.GetListByPage(pageSize, pageIndex, mySort, where));
        }

        public override void search(HttpContext context)
        {
            string areacode = context.Request.Params["areacode"]?? "";
            string deadname = context.Request.Params["deadname"]??"";
            string deadcode = context.Request.Params["deadcode"] ?? "";
            string relativename = context.Request.Params["relativename"]??"";
            string relativetel = context.Request.Params["relativetel"]??"";
            string paradiseCode = context.Request.Params["paradiseCode"] ?? "";
            string hourseNum = context.Request.Params["hourseNum"] ?? "";
            string floorNum = context.Request.Params["floorNum"] ?? "";
            string sectionNum = context.Request.Params["sectionNum"] ?? "";
            string lineNum = context.Request.Params["lineNum"] ?? "";
            string layerNum = context.Request.Params["layerNum"] ?? "";
            string colNum = context.Request.Params["colNum"] ?? "";
            string status = context.Request.Params["status"] ?? "";
            string where = context.Request.Params["where"] ?? "1=1";

            where = graveBLL.getWhere(where, status, paradiseCode, hourseNum, floorNum, sectionNum, lineNum, layerNum, colNum);
            int pageIndex = CommUtil.GetPageIndex(context);
            int pageSize = CommUtil.GetPageSize(context);
            string mySort = CommUtil.GetSort(context) + " " + CommUtil.GetOrder(context);

            context.Response.Write(graveBLL.GetListByPage(pageSize, pageIndex, mySort, where,areacode,deadname,relativename,relativetel,deadcode));
        }

        private void exportDead(HttpResponse resp, string loc)
        {            
            resp.Charset = "utf-8";
            resp.Clear();
            string name = graveBLL.getName(loc);
            string filename = "【" +name+ "】骨灰存放花名册" + DateTime.Now.ToString("yyyyMMddHHmmss");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            
            resp.ContentType = "application/ms-excel";
            string style = "<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>"
                + "<style> .table{ font: 13pt Tahoma, Verdana; color: #000000; text-align:center;border-collapse:collapse;border:solid #000 1px; } "
                + ".table td{text-align:center; border:solid #000 1px;} "
                + ".table th{text-align:center; font-weight: bold; padding:5px; border:solid #000 1px;} </style>";
            resp.Write(style);

            resp.Write("<table border='1' class='table'><tr><th colspan='9' >【" +name+ "】骨灰存放花名册</th></tr><tr><th>位置</th><th>联系人姓名</th><th>联系电话</th><th>村居委</th><th>家庭住址</th><th>死者姓名</th><th>与死者关系</th><th>骨灰类型</th><th>存放日期</th></tr>");
            var list = graveBLL.QueryList(loc);
            for (int i = 0; i < list.Count(); i++)
            {
                string row = string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td><td>{8:yyyy-MM-dd}</td></tr>",
                    list[i].graveName, list[i].relativeName, list[i].relativeTel, list[i].relativeAreaName, list[i].relativeAddr, list[i].name, list[i].relationId, list[i].storeType, list[i].storeTime);
                resp.Write(row);
            }
            resp.Write("</table>");
            resp.Flush();
        }

        public override void other(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string action = context.Request.Params["action"];
            switch (action)
            {
                case "gettree":
                    {
                        string strId = context.Request.Params["id"];
                        string strCode = context.Request.Params["code"];

                        if (string.IsNullOrEmpty(strId))
                        {
                            string json = graveBLL.getNavTopTree();
                            context.Response.Write(json);
                        }
                        else
                        {
                            int id = int.Parse(strId);
                            string json = graveBLL.getNavTree(id, strCode);
                            context.Response.Write(json);
                        }
                        break;
                    }
                case "export": {
                    string loc = context.Request.Params["loc"];
                    exportDead(context.Response,loc);
                    break;
                }
                case "import":
                    {
                        string op = context.Request.Params["op"];
                        if (op == "upload")
                        {
                            Cfg.IsRunning = false;
                            UserEntity user = UserService.GetUser(context);
                            //文件名  
                            HttpPostedFile f1 = context.Request.Files["ui_grave_import_file"];

                            string fileExt = System.IO.Path.GetExtension(f1.FileName);
                            if (!(fileExt == ".xls" || fileExt == ".xlsx"))
                            {
                                context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "只支持扩展名为.xls或.xlsx文件！" }));
                                return;
                            }
                            string fileName = user.userName + "_grave_" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;
                            f1.SaveAs(context.Server.MapPath("~/admin/upload/") + fileName);
                            context.Response.Write(JsonUtil.ToJson(new { success = true, msg = fileName }));
                        }
                        else if (op == "import")
                        {
                            
                            string file = context.Request.Params["ui_grave_import_filename"];
                            bool autocreate = context.Request.Params["autocreate"]=="1";

                            if (string.IsNullOrEmpty(file))
                            {
                                context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "文件未上传！" }));
                            }
                            else
                            {
                                try
                                {
                                    file = context.Server.MapPath("~/admin/upload/") + file;
                                    UserEntity user = UserService.GetUser(context);
                                    List<ImportModel> list = graveBLL.ImportExceltoDb(user,file, 0, 1, autocreate);
                                    Cfg.IsRunning = true;
                                    int cnt = graveBLL.Import(list, false);
                                    context.Response.Write(JsonUtil.ToJson(new { success = true, msg = "成功导入" + cnt + "个死者！" }));
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                                finally
                                {
                                    File.Delete(file);
                                }
                            }
                        }
                        break;
                    }
                case "clear":
                    {
                        string ids = context.Request.Params["ui_dead_id"];
                        string graveId = context.Request.Params["ui_grave_id"];
                        string remark = context.Request.Params["ui_grave_remark"];
                        context.Response.Write(graveBLL.removeDeadFromGrave(int.Parse(graveId), ids, remark));
                        break;
                    }
                case "move":
                    {
                        string graveId = context.Request.Params["ui_grave_id"];
                        string deadId = context.Request.Params["ui_dead_id"];

                        string paradiseCode = context.Request.Params["ui_grave_paradise_code"];
                        string hourse = context.Request.Params["ui_grave_hourseNum"];
                        string floor = context.Request.Params["ui_grave_floorNum"];
                        string section = context.Request.Params["ui_grave_sectionNum"];
                        string line = context.Request.Params["ui_grave_lineNum"];
                        string layer = context.Request.Params["ui_grave_rowNum"];
                        string column = context.Request.Params["ui_grave_colNum"];
                        string remark = context.Request.Params["ui_grave_move_remark"];
                        int oldGraveId = int.Parse(graveId);
                        int hourseNum = int.Parse(hourse);
                        int floorNum = int.Parse(floor);
                        try
                        {
                            int sectionNum = int.Parse(section);
                            section = string.Format("{0:00}", sectionNum);
                        }
                        catch { 
                        
                        }
                        int lineNum = int.Parse(line);
                        int layerNum = int.Parse(layer);
                        int colNum = int.Parse(column);
                       
                        tbGrave grave = new tbGrave
                        {
                            location = string.Format("{0}{1:0}{2:0}{3}{4:00}{5:00}{6:000}", paradiseCode, hourseNum, floorNum, section, lineNum, layerNum, colNum),
                            name = string.Format("{1}栋{2}楼{3}区{4}排{5}层{6}号", paradiseCode, hourseNum, floorNum, section, lineNum, layerNum, colNum),
                            hourseNum = hourse,
                            floorNum = floor,
                            sectionNum = section,
                            lineNum = string.Format("{0:00}", lineNum),
                            layerNum = string.Format("{0:00}", layerNum),
                            columnNum = string.Format("{0:000}", colNum)
                        };
                        if (string.IsNullOrEmpty(deadId))
                        {
                            context.Response.Write(graveBLL.Move(oldGraveId, grave, remark));
                        }
                        else
                        {
                            context.Response.Write(graveBLL.Move(oldGraveId, grave, int.Parse(deadId), remark));
                        }
                        break;
                    }
                case "store":
                    {
                        string op = context.Request.Params["op"];
                        bool bEditRelative = false; 
                        
                        if (op == "newrelative")
                        {
                            bEditRelative = true;
                        }
                        string graveId = context.Request.Params["ui_grave_id"];
                        int gid = int.Parse(graveId);
                        string notsave = context.Request.Params["ui_grave_notsave"];
                        bool bsave = true;
                        if (!string.IsNullOrEmpty(notsave)) bsave = false;

                        string deadId = context.Request.Params["ui_grave_dead_id"];
                        string deadName = context.Request.Params["ui_grave_dead_name"];
                        string deadCardNo = context.Request.Params["ui_grave_dead_cardno"];
                        string deadGender = context.Request.Params["ui_grave_dead_gender"];
                        string deadNation = context.Request.Params["ui_grave_dead_nation"];
                        string deadArea = context.Request.Params["ui_grave_dead_areaId"];
                        string relation = context.Request.Params["ui_grave_relative_relation"];
                        string storeType = context.Request.Params["ui_grave_store_type"];
                        string addr = context.Request.Params["ui_grave_dead_addr"];
                        string starttime = context.Request.Params["ui_grave_starttime"];
                        DateTime dt = DateTime.Now;
                        bool f = DateTime.TryParse(starttime, out dt);
                        if (string.IsNullOrEmpty(storeType))
                        {
                            storeType = "遗灰";
                        }
                        string fireTime = context.Request.Params["ui_grave_dead_firetime"];
                        tbDead dead = new tbDead();
                        if (!string.IsNullOrEmpty(deadId))
                        {
                            dead.id = int.Parse(deadId);
                        }
                        if (!string.IsNullOrEmpty(fireTime))
                        {
                            dead.actFiretime = DateTime.Parse(fireTime);
                        }
                        string desc = context.Request.Params["ui_grave_dead_desc"];
                        dead.description = desc;
                        dead.name = deadName;
                        dead.gender = deadGender;
                        dead.cardno = deadCardNo;
                        dead.nationid = deadNation;
                        dead.relationid = relation;
                        dead.storetype = storeType;
                        dead.areacode = deadArea;
                        dead.homeAddress = addr;
                        dead.birthAddress = addr;

                        if (f) dead.starttime = dt;
                        else
                            dead.starttime = DateTime.Now;

                        string relativeId = context.Request.Params["ui_grave_relative_id"];
                        string rName = context.Request.Params["ui_grave_relative_name"];
                        string rTel = context.Request.Params["ui_grave_relative_tel"];
                        string rArea = context.Request.Params["ui_grave_relative_areaId"];
                        string rCardno = context.Request.Params["ui_grave_relative_cardno"];


                        tbRelative relative = new tbRelative();
                        if (!string.IsNullOrEmpty(relativeId))
                        {
                            relative.id = int.Parse(relativeId);
                        }
                        relative.name = rName;
                        relative.tel = rTel;
                        relative.areacode = rArea;
                        relative.cardno = rCardno;


                        context.Response.Write(graveBLL.Store(dead, relative, gid, bsave, bEditRelative));
                        break;
                    }

                case "sellgrave":
                    {
                        string relativeId = context.Request.Params["ui_grave_relative_id"];
                        if (string.IsNullOrEmpty(relativeId))
                        {
                            context.Response.Write(JsonUtil.ToJson(new { success = false, msg = "请选择联系人!" }));
                            return;
                        }
                        string graveId = context.Request.Params["ui_grave_id"];
                        string paid = context.Request.Params["ui_grave_paid"];
                        int rid = int.Parse(relativeId);
                        int gid = int.Parse(graveId);
                        context.Response.Write(graveBLL.Sale(rid, gid, float.Parse(paid)));
                        break;
                    }
            }
        }        
    }
}